<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
      这题的重点在于不变量，每次循环的时候都要确定是左闭右开
      如果n%2==0 那么只需要从外到内循环即可
      如果n%2!=0 那么需要给中间额外赋值
      */
      var generateMatrix = function (n) {
        //创建数组
        let res = new Array(n);
        for (let i = 0; i < res.length; i++) {
          res[i] = new Array(n).fill(0);
        }
        //loop 循环次数 如果n是奇数，需要中间额外添加
        let loop = parseInt(n / 2);
        let startX = 0;
        let startY = 0;
        //定义中间值
        let mid = parseInt(n / 2);
        //count 赋值
        let count = 1;
        //定义的边界缩小值
        let offset = 1;
        let i = startX;
        let j = startY;
        while (loop--) {
          //每次循环开始的时候，都必须重新定义起点，不然i，j会有问题
          i = startX;
          j = startY;
          //从左往右
          for (; j < n - offset; j++) {
            res[i][j] = count++;
          }
          //从上往下
          for (; i < n - offset; i++) {
            res[i][j] = count++;
          }
          //从右往左  记住 左闭右开  你需要倒过来看
          for (; j > startY; j--) {
            res[i][j] = count++;
          }
          for (; i > startX; i--) {
            res[i][j] = count++;
          }
          //一圈结束
          startX++;
          startY++;
          offset += 1;
        }
        if (n % 2 == 1) {
          res[mid][mid] = count;
        }
        return res;
      };
      console.log(generateMatrix(4));
    </script>
  </body>
</html>
